package com.ruoyi.web.controller.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.ruoyi.common.enums.ProjectStatus;
import com.ruoyi.system.domain.vo.SysWhitePaperOutlineVo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysWhitePaperProject;
import com.ruoyi.system.service.ISysWhitePaperProjectService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 白皮书基本信息Controller
 *
 * @author ruoyi
 * @date 2025-10-18
 */
@RestController
@RequestMapping("/system/project")
public class SysWhitePaperProjectController extends BaseController
{
    @Autowired
    private ISysWhitePaperProjectService sysWhitePaperProjectService;

    /**
     * 查询白皮书基本信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:project:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysWhitePaperProject sysWhitePaperProject)
    {
        startPage();
        List<SysWhitePaperProject> list = sysWhitePaperProjectService.selectSysWhitePaperProjectList(sysWhitePaperProject);
        return getDataTable(list);
    }

    /**
     * 统计全部、执行中、已完成项目数量
     */
    @GetMapping("/statisticNum")
    public AjaxResult statisticNum() {
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("totalNum",0);
        resultMap.put("runNum",0);
        resultMap.put("finishNum",0);

        // 查询全部项目信息
        SysWhitePaperProject sysWhitePaperProject = new SysWhitePaperProject();
        List<SysWhitePaperProject> whitePaperProjectList = sysWhitePaperProjectService.selectSysWhitePaperProjectList(sysWhitePaperProject);
        if (CollectionUtils.isNotEmpty(whitePaperProjectList)) {
            // 执行中项目列表
            List<SysWhitePaperProject> runProjectList = whitePaperProjectList.stream().filter(project -> ProjectStatus.RUN.getCode().equals(project.getProjectStatus())).collect(Collectors.toList());
            // 已完成项目列表
            List<SysWhitePaperProject> finishProjectList = whitePaperProjectList.stream().filter(project -> ProjectStatus.FINISH.getCode().equals(project.getProjectStatus())).collect(Collectors.toList());

            resultMap.put("totalNum",whitePaperProjectList.size());
            resultMap.put("runNum",runProjectList.size());
            resultMap.put("finishNum",finishProjectList.size());
        }

        return AjaxResult.success(resultMap);
    }

    /**
     * 获取白皮书基本信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:project:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sysWhitePaperProjectService.selectSysWhitePaperProjectById(id));
    }

    /**
     * 停止项目
     */
    @PreAuthorize("@ss.hasPermi('system:project:stop')")
    @Log(title = "白皮书基本信息", businessType = BusinessType.UPDATE)
    @PostMapping("/stop")
    public AjaxResult stop(@RequestBody SysWhitePaperProject sysWhitePaperProject)
    {
        sysWhitePaperProjectService.stopSysWhitePaperProject(sysWhitePaperProject);
        return AjaxResult.success();
    }


    /**
     * 查询白皮书大纲列表，用于内容汇编页面左侧树展示
     */
    @GetMapping("/tree")
    public AjaxResult tree(Long id) {
        List<SysWhitePaperOutlineVo> outlineList = sysWhitePaperProjectService.selectSysWhitePaperOutlineList(id);

        List<Map<String, Object>> resultList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(outlineList)) {
            Map<Long, List<SysWhitePaperOutlineVo>> outlineMap = outlineList.stream().collect(Collectors.groupingBy(SysWhitePaperOutlineVo::getChapterId));
            Set<Long> chapterIdSet = outlineMap.keySet();

            for (Long chapterId : chapterIdSet) {
                List<SysWhitePaperOutlineVo> tempList = outlineMap.get(chapterId);
                List<Map<String, Object>> childrenList = Lists.newArrayList();
                for (SysWhitePaperOutlineVo outline : tempList) {
                    List<Map<String, Object>> secondChildrenList = Lists.newArrayList();
                    Map<String, Object> secondChildren = new HashMap<>();
                    secondChildren.put("id", outline.getId());
                    secondChildren.put("label", outline.getAiAnalyseResultTitle());
                    secondChildren.put("level", 3);
                    secondChildren.put("summary", "数据来源:" + outline.getDataSource());
                    secondChildren.put("content", outline.getAiAnalyseResult());
                    secondChildren.put("finalContent", outline.getFianlAnalyseResult());
                    secondChildren.put("createTime", outline.getCreateTime());

                    secondChildrenList.add(secondChildren);

                    Map<String, Object> children = new HashMap<>();
                    children.put("id", outline.getId());
                    children.put("level", 2);
                    children.put("label", outline.getTitle());
                    children.put("children", secondChildrenList);
                    childrenList.add(children);
                }
                SysWhitePaperOutlineVo temp = tempList.get(0);

                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("id", chapterId);
                resultMap.put("level", 1);
                resultMap.put("label", temp.getChapterName());
                resultMap.put("children", childrenList);
                resultList.add(resultMap);
            }
        }

        return success(resultList);
    }

    /**
     * 查询白皮书大纲列表，用于大纲页面反显
     */
    @GetMapping("/detailList")
    public AjaxResult detailList(Long id) {
        List<SysWhitePaperOutlineVo> outlineList = sysWhitePaperProjectService.selectSysWhitePaperOutlineList(id);

        List<Map<String, Object>> whitePaperChapterList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(outlineList)) {
            Map<Long, List<SysWhitePaperOutlineVo>> outlineMap = outlineList.stream().collect(Collectors.groupingBy(SysWhitePaperOutlineVo::getChapterId));
            Set<Long> chapterIdSet = outlineMap.keySet();

            for (Long chapterId : chapterIdSet) {
                List<SysWhitePaperOutlineVo> tempList = outlineMap.get(chapterId);
                Map<String, Object> whitePaperChapterMap = new HashMap<>();
                whitePaperChapterMap.put("chapterName", tempList.get(0).getChapterName());
                whitePaperChapterMap.put("outlineList", tempList);

                whitePaperChapterList.add(whitePaperChapterMap);
            }
        }

        return success(whitePaperChapterList);
    }

}
